package app.server.project.main.service.db.dao.user;


import app.server.project.main.service.db.entity.user.UserActiveEntity;
import app.server.project.main.service.db.mapper.user.UserActiveMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Objects;

@Repository
public class UserActiveDao extends ServiceImpl<UserActiveMapper, UserActiveEntity> {

    @Cacheable(key = "#userId", cacheNames = "app.server.project.main.service.db.dao.UserActiveDao")
    public UserActiveEntity getInfoById(long userId) {
        var data = this.getById(userId);
        if (Objects.isNull(data)) {
            //缓存没有,就往库中写入一条数据
            data = UserActiveEntity.of(userId);
        }
        data.setSynDb(true);
        return data;
    }

    public long countActive(LocalDateTime start, LocalDateTime end) {
        return this.count(Wrappers.lambdaQuery(UserActiveEntity.class)
                .ge(UserActiveEntity::getLastLoginTime, start)
                .le(UserActiveEntity::getLastLoginTime, end));
    }
}
